package com.ruoyi.web.controller.ex;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.doudou.core.container.ListUtil;
import com.ruoyi.ex.domain.ExEnum;
import com.ruoyi.ex.domain.ExQuestion;
import com.ruoyi.ex.domain.ExStudyReload;
import com.ruoyi.ex.service.ExService;
import com.ruoyi.ex.service.IExQuestionService;
import com.ruoyi.ex.service.IExStudyReloadService;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.service.IPvStudentRecordService;
import com.ruoyi.pv.service.IPvTrainingClassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ex.domain.ExQuestionBank;
import com.ruoyi.ex.service.IExQuestionBankService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 题库Controller
 *
 * @author zzx
 * @date 2023-03-23
 */
@Api("题库")
@RestController
@RequestMapping("/ex/question_bank")
public class ExQuestionBankController extends BaseController {

    @Autowired private IExQuestionBankService exQuestionBankService;
    @Autowired private IExStudyReloadService exStudyReloadService;
    @Autowired private IPvStudentRecordService studentRecordService;
    @Autowired private IPvTrainingClassService classService;
    @Autowired private ExService exService;
    @Autowired private IExQuestionService questionService;

    /**
     * 查询当前机构的可报名考题
     * <p>
     *     data.status 题库状态 【不看】
     *     data.ok => 0:可以考试 、 1:尚未开始 、 2:已结束 【不看】
     *     data.applyOk => 是否可以预约（是否在时间范围内）  true:可以预约、false：不用预约 【预约考试用】
     *     reload.status => 1：可以开始考试 、 3：已完成考试 【不看】
     *     masterStatus => 0可以考试、 1未到考试时间、 2已结束（未作答，无法查看试卷）、 3已结束（作答完毕，可查看试卷）、4未报名 【综合】
     * </p>
     */
    @GetMapping("/apply")
    @ApiOperation("查询当前机构的可报名考题")
    public AjaxResult apply() {
        Long deptId = getDeptId();
        //获取当前登录用户的权限
        PvUserInfo userInfo = getUserInfo(PvUserInfo.class);
        //获取当前登录用户的培训班
        PvStudentRecord studentRecord = studentRecordService.thisYearHas(userInfo.getId());
        if (ObjectUtil.isEmpty(studentRecord)){
            return AjaxResult.error("未查询到报名班");
        }
        ExQuestionBank build = ExQuestionBank.builder().
                classId(studentRecord.getTraining()).//培训班
                deptId(deptId).
                trainFlag(Integer.valueOf(userInfo.getReservedOne())).//初复训
                status(0).build();
        List<ExQuestionBank> questionBank = exQuestionBankService.selectExQuestionExList(build);
        if (CollUtil.isNotEmpty(questionBank)){
            build = questionBank.get(0);
            build.setClazz(classService.selectPvTrainingClassById(studentRecord.getTraining()));
            ExStudyReload exStudyReload = ExStudyReload.builder().
                    stuId(userInfo.getId()).
                    deptId(deptId).
                    bankId(build.getId()).
                    build();
            //查询考试预约记录
            List<ExStudyReload> exStudyReloads = exStudyReloadService.selectExStudyReloadList(exStudyReload);
            if (CollUtil.isNotEmpty(exStudyReloads)){
                exStudyReload = exStudyReloads.get(0);
                if (exStudyReload.getStatus().equals(3)){
                    Map<Long, Boolean> questionAnswers = new HashMap<>();
                    //格式化已回答列表
                    List<Long> questionIds = questionService.selectIdsByBankId(exStudyReload.getBankId());
                    Map<Long, Object> answerMap = exService.rightTotal(exStudyReload.getAnswerMap(),questionIds);
                    for (Long questionId : questionIds) {
                        questionAnswers.put(questionId,answerMap.containsKey(questionId));
                    }
                    exStudyReload.setQuestionAnswers(questionAnswers);
                }else if (exStudyReload.getStatus().equals(0) || exStudyReload.getStatus().equals(1)){
                    build.resetOk(exStudyReload.getExDate(),exStudyReload.getExTimeObj());
                }
            }else {
                exStudyReload = null;
            }
            int status;
            if (ObjectUtil.isEmpty(exStudyReloads)){
                status = ExEnum.NOT_APPLY.get();
            }else{
                status = (!exStudyReload.getStatus().equals(1)) ? ExEnum.IS_OVER_LOOK_EX.get() : build.getOk();
            }
            if (exStudyReload != null && exStudyReload.getQuestionIds() != null){
                exStudyReload.setQuestionIds(ListUtil.disrupt(exStudyReload.getQuestionIds()));
            }

            return success(build).put("reload",exStudyReload).put("masterStatus",status);
        }else {
            return error("未查询到可报名考题");
        }
    }

    /**
     * 根据题库获取所有题目
     */
    @GetMapping("/all-question/{bankId}")
    public AjaxResult allQuestion(@PathVariable("bankId")Long bankId){
        List<ExQuestion> questions = questionService.selectIdsByBankId(bankId).
                stream().map(id -> questionService.selectExQuestionById(id)).
                collect(Collectors.toList());
        return success(questions);
    }


    /**
     * 保存答案列表到缓存
     */
    @PostMapping("/save-answers/{bankId}")
    @ApiOperation("保存答案列表到缓存")
    public AjaxResult saveAnswers(@PathVariable("bankId")Long bankId,@RequestBody JSONObject answers){
        try{
            exQuestionBankService.saveAnswers(getUserId(),bankId,answers);
            return AjaxResult.success("保存成功");
        }catch (Exception e){
            logger.error("",e);
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 从缓存中获取答案
     */
    @GetMapping("/get-answers/{bankId}")
    @ApiOperation("从缓存中获取答案")
    public AjaxResult getAnswers(@PathVariable("bankId")Long bankId){
        try{
            return AjaxResult.success(exQuestionBankService.getAnswers(getUserId(),bankId));
        }catch (Exception e){
            logger.error("",e);
            return AjaxResult.success(new JSONObject());
        }
    }

    /**
     * 查询题库列表
     */
    @GetMapping("/list-ex")
    @ApiOperation("查询题库列表")
    public TableDataInfo listEx(ExQuestionBank exQuestionBank) {
        startPage();
        exQuestionBank.setDeptId(getDeptId());
        List<ExQuestionBank> list = exQuestionBankService.selectExQuestionExList(exQuestionBank);
        return getDataTable(list);
    }

    /**
     * 查询题库列表
     */
    @GetMapping("/list")
    @ApiOperation("查询题库列表")
    public TableDataInfo list(ExQuestionBank exQuestionBank) {
        startPage();
        exQuestionBank.setDeptId(getDeptId());
        exQuestionBank.setIsEx(0);
        List<ExQuestionBank> list = exQuestionBankService.selectExQuestionBankList(exQuestionBank);
        return getDataTable(list);
    }

    /**
     * 导出题库列表
     */
    @PreAuthorize("@ss.hasPermi('ex:question_bank:export')")
    @Log(title = "题库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExQuestionBank exQuestionBank) {
        exQuestionBank.setDeptId(getDeptId());
        List<ExQuestionBank> list = exQuestionBankService.selectExQuestionBankList(exQuestionBank);
        ExcelUtil<ExQuestionBank> util = new ExcelUtil<ExQuestionBank>(ExQuestionBank.class);
        util.exportExcel(response, list, "题库数据");
    }

    /**
     * 获取题库详细信息
     */

    @GetMapping(value = "/{id}")
    @ApiOperation("获取题库详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(exQuestionBankService.selectExQuestionBankById(id));
    }

    /**
     * 新增题库
     */
    @PreAuthorize("@ss.hasPermi('ex:question_bank:add')")
    @Log(title = "题库", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增题库")
    public AjaxResult add(@RequestBody ExQuestionBank exQuestionBank) {
        exQuestionBank.setDeptId(getDeptId());
        exQuestionBank.setStatus(0);//默认为启用
        if (exQuestionBank.getIsEx().equals(1)){//如果是考试题库，组装唯一标识
            exQuestionBank.parseUniqueFlag();
        }
        return toAjax(exQuestionBankService.insertExQuestionBank(exQuestionBank));
    }

    /**
     * 修改题库
     */
    @Log(title = "题库", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改题库")
    public AjaxResult edit(@RequestBody ExQuestionBank exQuestionBank) {
        if (exQuestionBank.getIsEx().equals(1)){//如果是考试题库，组装唯一标识
            exQuestionBank.parseUniqueFlag();
        }
        return toAjax(exQuestionBankService.updateExQuestionBank(exQuestionBank));
    }

    /**
     * 删除题库
     */
    @Log(title = "题库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除题库")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(exQuestionBankService.deleteExQuestionBankByIds(ids));
    }

    /**
     * 发送短信通知-人数
     */
    @Log(title = "发送短信通知-人数", businessType = BusinessType.OTHER)
    @PostMapping("/smsSend-people-count")
    public AjaxResult smsSendPeopleCount(@RequestBody JSONObject body) {
        return success(exQuestionBankService.smsSendPeopleCount(body.getBeanList("classIds",Long.class),body.getInt("trainFlag")));
    }

    /**
     * 发送短信通知
     */
    @Log(title = "发送短信通知", businessType = BusinessType.OTHER)
    @PostMapping("/smsSend/{id}")
    @ApiOperation("删除题库")
    public AjaxResult smsSend(@PathVariable Long id,@RequestBody JSONObject body) {
        exQuestionBankService.smsSend(id,body.getBeanList("classIds",Long.class),body.getInt("trainFlag"));
        return success();
    }
}
